import { EntityModel } from '@midwayjs/orm';
import { createHash } from 'crypto';
import { BeforeInsert, Column, ManyToOne, OneToOne } from 'typeorm';
import { BaseModel } from '../utils/base.model';
import * as _ from 'lodash';
import { Department } from './Department';

export enum UserType {
  ADMIN = 'admin',
  NORMAL = 'normal',
  WECHAT = 'wechat',
}

@EntityModel()
export class User extends BaseModel {
  @Column()
  username: string;

  @Column()
  password: string;

  @Column()
  salt: string;

  @Column({ nullable: true })
  nickname: string;

  @Column({ nullable: true })
  avatarUrl: string;

  @Column({ nullable: true })
  openid: string;

  @Column({ nullable: true })
  idcard: string;

  @Column({ nullable: true })
  province: string;

  @Column({ nullable: true })
  city: string;

  @Column({ default: 0 })
  integral: number;

  @Column({
    type: 'enum',
    enum: UserType,
    default: UserType.NORMAL,
  })
  type: string;

  @ManyToOne(() => Department)
  department: Department;

  @BeforeInsert()
  hashPassword() {
    const md5 = createHash('md5');
    this.salt = Math.random().toString().slice(2, 8);
    this.password = md5.update(`${this.password}:${this.salt}`).digest('hex');
  }

  validatePassword(password) {
    const md5 = createHash('md5');
    const _password = md5.update(`${password}:${this.salt}`).digest('hex');
    return this.password === _password;
  }

  async changePassword(password) {
    const md5 = createHash('md5');
    const _password = md5.update(`${password}:${this.salt}`).digest('hex');
    this.password = _password;
  }

  toJSON() {
    // 排除密码和盐
    return _.omit(this, ['password', 'salt', 'openid']);
  }
}
